package cn.fl.project.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.api.IMcrBillMApiService;
import cn.fl.mcr.condition.McrBillMQC;
import cn.fl.mcr.constant.McrBillMConstant;
import cn.fl.mcr.dto.McrBillMDTO;
import cn.fl.project.condition.PrjPaySchMYqQC;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPaySchMYqConstant;
import cn.fl.project.service.IPrjPaySchMYqService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjPaySchMYqVO;
import cn.fl.project.vo.PrjPaySchMYqWebVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;

/**
 * @Description: 疫情项目与支付表关系表信息 控制层
 */
@Controller
@RequestMapping("/project/prjPaySchMyq")
public class PrjPaySchMYqController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PrjPaySchMYqController.class);

    /**
     * PrjPaySchMYq 服务层BEAN
     */
    @Autowired
    private IPrjPaySchMYqService prjPaySchMYqService;
    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;
    /**
     * 主账单API服务
     */
    @Autowired
    private IMcrBillMApiService mcrBillMApiService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("/prjPaySchMYq/prjPaySchMYqList");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        ModelAndView view = new ModelAndView("/prjPaySchMYq/prjPaySchMYqAdd");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载新增.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("/prjPaySchMYq/prjPaySchMYqModify");
        view.addObject("id", id);
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toAddPage", "加载修改.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", "加载例子详细页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("/prjPaySchMYq/prjPaySchMYqDetail");
        view.addObject("id", id);

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toDetailPage", " 加载例子详细页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());


        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String searchName = request.getParameter("demo.name");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        PrjPaySchMYqQC qc = new PrjPaySchMYqQC();
        if (StringUtils.isNotEmpty(searchName)) {
            //TODO SOMTHING
        }
        page.setCondition(qc);
        Pager pager = this.prjPaySchMYqService.searchListPage(page);
        List<PrjPaySchMYqVO> list = (List<PrjPaySchMYqVO>) pager.getResultList();
        ListPageVO<PrjPaySchMYqVO> listPage = new ListPageVO<PrjPaySchMYqVO>(list, pager.getTotalCount());
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }

    /**
     * 查询疫情可用支付表列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getPrjPrdPaySchMList.do", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object getPrjPaySchMYQList(HttpServletRequest request, HttpServletResponse response) {
        String prjId = request.getParameter("prjId");
        String prjTypCd = request.getParameter("prjTypCd");//项目类型
        String cstId = request.getParameter("cstId");//客户ID
        String detailFlag = request.getParameter("detailFlag");//查询状态
        String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");//客户经理的组织机构
        String buOrgCd = request.getParameter("buOrgCd");//客户经理的组织机构
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
        if (StringUtils.isEmpty(prjTypCd) || StringUtils.isEmpty(cstId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("参数不完整！");
            return result;
        } else if (!PrjBscInfoConstant.PRJ_TYP_CD_CDDYWYQ.equals(prjTypCd)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("非疫情项目！");
            return result;
        }
        try {
            PrjPaySchMYqQC qc = new PrjPaySchMYqQC();
            if(StringUtils.isNotEmpty(prjId)){
                qc.setPrjId(Long.valueOf(prjId));
            }
            qc.setCstId(Long.valueOf(cstId));
            McrBillMQC mcrBillMQC = new McrBillMQC();
            mcrBillMQC.setCstId(Long.valueOf(cstId));
            String crtTmStr = DateUtils.formatDateToString(DateUtils.formatStringToDate("2020-01-01 00:00:00",DateUtils.YYYY_MM_DDHHMMSS), DateUtils.YYYY_MM_DDHHMMSS);
            mcrBillMQC.setCrtTmStrBig(crtTmStr);
            //查看
            if(StringUtils.isNotEmpty(detailFlag) && "true".equals(detailFlag) && StringUtils.isNotEmpty(prjId)){
                qc.setSelectTypCd("0");
            //新增活修改
            }else{
                qc.setSelectTypCd("1");
            }
            // 去掉小贷限制
         /*   List<String> loanStsCdList = new ArrayList<>();
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_1);
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_2);
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_3);
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_4);
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_5);
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_6);
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_7);
            loanStsCdList.add(McrBillMConstant.LOAN_STS_CD_8);
            mcrBillMQC.setLoanStsCdList(loanStsCdList);
            BaseLogUtils.info(logger, "getPrjPaySchMYQList", "客户查询小贷详情 QC>>." + JSON.toJSONString(mcrBillMQC), CurrentThreadContext.getCurrentUserName());
            List<McrBillMDTO> mcrBillMDTOS = this.mcrBillMApiService.searchMcrBillMDTOList(mcrBillMQC);
            BaseLogUtils.info(logger, "getPrjPaySchMYQList", "客户查询小贷详情 QC>>." + JSON.toJSONString(mcrBillMQC)
                    +"结果 mcrBillMDTOS >> "+ JSONArray.toJSONString(mcrBillMDTOS), CurrentThreadContext.getCurrentUserName());
            if(CollectionUtils.isNotEmpty(mcrBillMDTOS)){
                throw new BaseException("客户2020年后申请过小贷,不能做车抵贷疫情项目");
            }*/
            List<PrjPaySchMYqWebVO> voList = this.prjPaySchMYqService.getPrjPrdPaySchMList(qc);
            //支持疫情贷资方配置
            List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup("11000", "0000", PrjPaySchMYqConstant.YQ_SP_INS_CD);
            List<String> insCodeList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
                for(SysDictionaryDTO dicDto : sysDictionaryDTOList){
                    if(StringUtils.isEmpty(dicDto.getCodeAttr1()) || StringUtils.isEmpty(dicDto.getCode()) ){
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("资产资管业务配置查收数据失败！");
                        return result;
                    }
                    // 是否支持 Y 支持就做
                    if(PrjPaySchMYqConstant.IS_INS_TYP_CD_YES.equals(dicDto.getCodeAttr1())){
                        insCodeList.add(dicDto.getCode());
                    }
                }
                /**
                 * 如果有可支持的机构编码执行如下查询
                 */
                if(CollectionUtils.isNotEmpty(insCodeList)){
                    qc.setPrjInsTypCdList(insCodeList);
                    List<PrjPaySchMYqWebVO> voZfList = this.prjPaySchMYqService.getPrjPrdPaySchMForZfList(qc);
                    if(CollectionUtils.isNotEmpty(voZfList)){
                        voList.addAll(voZfList);
                    }
                }
            }
            Map m = new HashMap<>();
            m.put("yqList", voList);
            result.setData(m);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            logger.error(ex.getMessage(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("获取数据失败！");
            logger.error("获取数据失败！", ex);
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        PrjPaySchMYqVO entity = null;
        try {
            entity = new PrjPaySchMYqVO();
            //TODO ADD PARAM
            Long id = this.prjPaySchMYqService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "add", "新增数据.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "add", "新增对象失败,name[" + name + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", "新增对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("数据不存在!");
            BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        PrjPaySchMYqVO entity = null;
        try {
            entity = new PrjPaySchMYqVO();
            entity.setId(Long.valueOf(id));
            //entity.setName(name);
            //TODO ADD PARAM
            boolean success = this.prjPaySchMYqService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
                BaseLogUtils.info(logger, "modify", "修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改成功.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "modify", "修改对象失败,id[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", "修改对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            this.prjPaySchMYqService.removeById(Long.valueOf(id));
            BaseLogUtils.info(logger, "removeById", "删除数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "remove", "移除对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "remove", "移除对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            PrjPaySchMYqVO vo = this.prjPaySchMYqService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.error(logger, "getById", "根据主键获取对象失败,主键[" + id + "].", CurrentThreadContext.getCurrentUserName(), ex);
        }

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", "根据主键获取对象.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());

        return result;
    }
}

